import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: { title: '工作台', icon: 'HomeFilled' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/User/index.vue'),
        meta: { title: '用户管理', icon: 'User' }
      },
      {
        path: 'product',
        name: 'Product',
        component: () => import('@/views/Product/index.vue'),
        meta: { title: '商品管理', icon: 'Goods' }
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('@/views/Order/index.vue'),
        meta: { title: '订单管理', icon: 'Document' }
      },
      {
        path: 'asset',
        name: 'Asset',
        redirect: '/asset/list',
        meta: { title: '资产管理', icon: 'OfficeBuilding' },
        children: [
          {
            path: 'list',
            name: 'AssetList',
            component: () => import('@/views/Asset/AssetList/index.vue'),
            meta: { title: '资产列表', icon: 'List' }
          },
          {
            path: 'gateway',
            name: 'GatewayList',
            component: () => import('@/views/Asset/GatewayList/index.vue'),
            meta: { title: '网关列表', icon: 'Router' }
          },
          {
            path: 'distribution',
            name: 'DistributionList',
            component: () => import('@/views/Asset/DistributionList/index.vue'),
            meta: { title: '配电间列表', icon: 'Connection' }
          }
        ]
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings/index.vue'),
        meta: { title: '系统设置', icon: 'Setting' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.path === '/login') {
    next()
  } else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
